﻿using QLHREntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QLHuongRungDAO
{
    public class ThucDonDAO
    {
        private QLHuongRungEntities db = new QLHuongRungEntities();
        public ThucDonDAO() { }

        public List<ThucDon> LayDanhSachThucDon()
        {
            List<ThucDon> result = new List<ThucDon>();
            var data = from td in db.ThucDons
                       select td;
            if(data != null)
                result = data.ToList();
            return result;
            
        }

        public void ThemThucDonMoi(DateTime dtBatDau, DateTime dtKetThuc)
        {
            ThucDon thucdon = new ThucDon();
            thucdon.NgayBatDau = dtBatDau;
            thucdon.NgayKetThuc = dtKetThuc;
            thucdon.TinhTrangDatHang = 0;
            db.ThucDons.Add(thucdon);
            db.SaveChanges();
        }

        public void ThemChiTietThucDonMoi(List<MonAn> thucdonmoi)
        {
            int maThucdon = 1;
            var thucdon = (from td in db.ThucDons
                        orderby td.MaThucDon descending
                        select td).ToList();
            if(thucdon.Count > 0)
                maThucdon = thucdon.First().MaThucDon;
            foreach (var item in thucdonmoi)
            {
                var chitietmonan = (from ctma in db.ChiTietMonAns
                            where ctma.MonAn == item.MaMonAn
                            select ctma).ToList();
                foreach (var nl in chitietmonan)
                {
                    ChiTietThucDon cttd = new ChiTietThucDon();
                    cttd.ThucDon = maThucdon;
                    cttd.NguyenLieu = nl.NguyenLieu;
                    cttd.MonAn = nl.MonAn;
                    db.ChiTietThucDons.Add(cttd);
                }
            }
            db.SaveChanges();
        }

        public List<ThucDon> LayDanhSachDatHang()
        {
            List<ThucDon> result = new List<ThucDon>();
            var data = from td in db.ThucDons
                       where td.TinhTrangDatHang == 0
                       select td;
            if (data != null)
                result = data.ToList();
            return result;
        }

        public void CapNhatDangDatHang(int maThucDon)
        {
            ThucDon thucDon = (from td in db.ThucDons
                                             where td.MaThucDon == maThucDon
                                             select td).First();
            thucDon.TinhTrangDatHang = 1;
            db.Entry(thucDon).State = System.Data.EntityState.Modified;
            db.SaveChanges();
        }
    }
}
